package com.tingyun.sign.activity.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tingyun.sign.activity.service.ActivityService;
import com.tingyun.sign.core.entity.ScActivityBean;
import com.tingyun.sign.core.repository.ActivityDao;
import com.tingyun.sign.utils.DateUtils;
import com.tingyun.sign.utils.MyAssert;
import com.tingyun.sign.utils.Page;

@Service("activityService")
public class ActivityServiceImpl implements ActivityService {

	private static Logger log = LoggerFactory.getLogger(ActivityServiceImpl.class);

	@PersistenceContext(name = "jpa")
	private EntityManager entityManager;
	@Autowired
	private ActivityDao activityDao;
	
	@Override
	public Integer addActivity(ScActivityBean bean) {
		MyAssert.notNull(bean, "参数为空");
		MyAssert.notNull(bean.getTopic(), "[活动名称]为空");
		MyAssert.notNull(bean.getArea(), "[活动类型]为空");
		//判断活动名称是否存在
		checkTopic(bean);
		try {
			activityDao.save(bean);
		} catch (Exception e) {
			log.error("活动添加失败", e);
			MyAssert.isTrue(false, "系统异常，添加活动失败，请稍后重试");
		}
		return 1;
	}

	private void checkTopic(ScActivityBean bean) {
		Integer num = 0;
		if(bean.getId()==null) {
			num = activityDao.findByTopic(bean.getTopic(), bean.getArea());
			
		}else {
			num = activityDao.findByTopicAndId(bean.getId(), bean.getTopic());
		}
		if(num>0) {
			MyAssert.isTrue(false,"活动名称已存在，请修改再提交");
		}
	}

	/**
	 * 根据管理员类型查找对应的活动列表
	 */
	@Override
	public Page<ScActivityBean> findActivitiesByType(ScActivityBean bean) {
		//必填参数校验
		MyAssert.notNull(bean, "参数为空");
		//分页查询
		Page<ScActivityBean> page = new Page<ScActivityBean>();
		Integer total = 0;
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<ScActivityBean> cq = cb.createQuery(ScActivityBean.class);
		Root<ScActivityBean>  root = cq.from(ScActivityBean.class);
		List<Predicate> pres = new ArrayList<Predicate>();
		pres.add(cb.greaterThanOrEqualTo(root.<Date>get("ctime"), bean.getStartTime()));
		pres.add(cb.lessThan(root.<Date>get("ctime"), DateUtils.addDay(bean.getEndTime(), 1)));
		//整合查询条件
		if(StringUtils.isNotBlank(bean.getTopic())) {
			pres.add(cb.like(root.<String>get("topic"), "%"+bean.getTopic()+"%"));
		}
		if(bean.getArea()!=0) {
			pres.add(cb.equal(root.get("area"), bean.getArea()));
			//根据type查询总数
			if(bean.getStatus()!=null) {
				total = activityDao.countByTypeByStatus(bean.getArea(),bean.getStartTime(),DateUtils.addDay(bean.getEndTime(), 1),bean.getStatus());
			}else {
				total = activityDao.countByType(bean.getArea(),bean.getStartTime(),DateUtils.addDay(bean.getEndTime(), 1));
			}
		}else {
			//查询总数
			if (bean.getStatus()!=null) {
				total = activityDao.countEffectiveAcsByStatus(bean.getStartTime(),DateUtils.addDay(bean.getEndTime(),1),bean.getStatus());
			} else {
				total = activityDao.countEffectiveAcs(bean.getStartTime(),DateUtils.addDay(bean.getEndTime(),1));
			}
		}
		if(bean.getStatus()!=null) {
			pres.add(cb.equal(root.get("status"), bean.getStatus()));
		}
		Predicate p = cb.and(pres.toArray(new Predicate[pres.size()]));
		cq.where(p);//and
		cq.orderBy(cb.desc(root.get("id")));//排序
		//执行查询
		TypedQuery<ScActivityBean> query = entityManager.createQuery(cq);
		query.setFirstResult(bean.getStart());
		query.setMaxResults(bean.getPageSize());
		List<ScActivityBean> list = query.getResultList();
		page.setResultList(list);
		//查询总数
		page.setTotalCount(total);
		return page;
	}

	@Override
	@Transactional
	public Integer updateActivity(ScActivityBean bean) {
		MyAssert.notNull(bean, "参数为空");
		MyAssert.notNull(bean.getTopic(), "[活动名称]为空");
		MyAssert.notNull(bean.getArea(), "[活动类型]为空");
		//判断活动名称是否存在
		checkTopic(bean);
		try {
			activityDao.updateById(bean.getId(), bean.getArea(),bean.getTopic(),bean.getRemark(),bean.getMuser());
		} catch (Exception e) {
			log.error("活动添加失败", e);
			MyAssert.isTrue(false, "系统异常，添加活动失败，请稍后重试");
		}
		return 1;
	}
	
	@Override
	@Transactional
	public Integer deleteById(ScActivityBean bean) {
		MyAssert.notNull(bean, "参数为空");
		MyAssert.notNull(bean.getId(), "[活动ID]为空");
		//判断活动名称是否存在
		checkTopic(bean);
		try {
			activityDao.deleteById(bean.getId(),bean.getMuser());
		} catch (Exception e) {
			log.error("活动添加失败", e);
			MyAssert.isTrue(false, "系统异常，添加活动失败，请稍后重试");
		}
		return 1;
	}
	
	@Override
	public List<ScActivityBean> findAllActivities(Integer type) {
		if(type==0) {
			return activityDao.findAllActivities();
		}
		return activityDao.findAllActivities(type);
	}
}
